package com.gzhryc.shared_device.oem.h5.agent.mng.jetty;

import java.util.EnumSet;

import javax.servlet.DispatcherType;

import com.gzhryc.shared_device.oem.h5.agent.mng.WebConstants;
import org.eclipse.jetty.server.Connector;
import org.eclipse.jetty.server.Handler;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.server.handler.DefaultHandler;
import org.eclipse.jetty.server.handler.HandlerCollection;
import org.eclipse.jetty.server.session.SessionHandler;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.util.resource.Resource;

import com.gzhryc.common.config.PropertyTools;
import com.gzhryc.common.logging.Logger;

/**
 * Jetty服务
 * 
 * @author zhanghao
 *
 */
public class JettyHttpServer {

	final static Logger log = Logger.getLogger(JettyHttpServer.class);

	public static void start(String path) throws Exception {
		Server server = new Server();

		ServerConnector connector = new ServerConnector(server);
		connector.setPort(PropertyTools.get().getInt(WebConstants.PROGRAM_TYPE + ".Jetty.port"));
		connector.setIdleTimeout(90000L);
		server.setConnectors(new Connector[] { connector });

		ServletContextHandler context = new ServletContextHandler();
		context.setContextPath("/");
		context.addServlet(MainServlet.class, "/*");
		String webapp = PropertyTools.get().getString(WebConstants.PROGRAM_TYPE + ".webapp");
		context.setBaseResource(Resource.newResource(webapp));

		SessionHandler sh = new SessionHandler();
		sh.setMaxInactiveInterval(420);   //最大非活动间隔，7分钟
		context.setSessionHandler(sh);

		context.addFilter(CommonFilter.class, "/*", EnumSet.of(DispatcherType.REQUEST));
		context.addFilter(HtmlSecurityFilter.class, "*.html", EnumSet.of(DispatcherType.REQUEST));
		context.addFilter(AjaxSecurityFilter.class, "*.do", EnumSet.of(DispatcherType.REQUEST));
		context.addFilter(AjaxSecurityFilter.class, "*.data", EnumSet.of(DispatcherType.REQUEST));
		context.addFilter(AjaxSecurityFilter.class, "*.jpg", EnumSet.of(DispatcherType.REQUEST));

		HandlerCollection handlers = new HandlerCollection();
		handlers.setHandlers(new Handler[] { context, new DefaultHandler() });
		server.setHandler(handlers);

		log.info("启动Jetty HTTP服务，端口：" + connector.getPort());

		server.start();
		server.join();
	}
}
